package org.sky.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.log4j.Logger;
import org.sky.service.PersonService;
import org.sky.vo.PersonVO;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.annotation.Resource;


@Component("login")
@Scope("prototype")
public class LoginAction extends ActionSupport implements ModelDriven<PersonVO> {

    private PersonService personService;

    private final PersonVO personVO = new PersonVO();

    private final static Logger logger = Logger.getLogger(LoginAction.class);

    SessionRegistry sessionRegistry;
    @ModelAttribute("numUsers")
    public int getNumberOfUsers() {
        return sessionRegistry.getAllPrincipals().size();
    }
/*    //用户登录
@Override
public String execute() throws Exception {

    if (personVO.getUserName() == null) return ERROR;

    Person person = personService.findPersonByUserName(personVO.getUserName());

    if (person == null) return ERROR;


    if (personVO.getPassword().equals(person.getPassword())) {
        System.out.print(personVO.getGroupName().equals(person.getAuthority().getAuthority()));
        if(!personVO.getGroupName().equals(person.getAuthority().getAuthority()))
            return ERROR;
        if (person.getAuthority() == null) {
            personVO.setResultMessage("您还没有分配相应的角色,不存在任何权限!请找相关人士联系!");
            return "message";
        }

        storePersonToSession(person);
logger.info("user:" + person.getUserName() + ", group:"
                + person.getAuthority().getAuthority() + " login the system.");

        return SUCCESS;
    }
    return ERROR;

}

public String loginOut() throws Exception {
    HttpSession session = ServletActionContext.getRequest().getSession();
    Person person = (Person) session.getAttribute("person");
    if (person != null) {
        logger.info(person.getUserName() + " leave the system by security way");
        session.removeAttribute("person");
        session.invalidate();
    }
    return "loginOut";
}*/

    @Override
    public PersonVO getModel() {
        return personVO;
    }

    @Resource(name = "personServiceImpl")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

 /*   private void storePersonToSession(Person target) {
        HttpSession session = ServletActionContext.getRequest().getSession();
        Person storedPerson = (Person) session.getAttribute("person");
        if (storedPerson == null || !storedPerson.equals(target)) {
            session.setAttribute("person", target);
            session.setMaxInactiveInterval(-1);
        }
    }*/
}
